package org.scrumpmt.web;

import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.scrumpmt.domain.Estado;
import org.scrumpmt.domain.Proyecto;
import org.scrumpmt.domain.Sprint;
import org.scrumpmt.domain.Tarea;
import org.scrumpmt.ejb.EstadoFacade;
import org.scrumpmt.ejb.SprintFacade;
import org.scrumpmt.ejb.TareaFacade;

/**
 *
 * Esta clase devuelve el listado de Sprints asociados a un Producto
 *
 * @author agumpg
 */
@ManagedBean(name = "sprintBean")
@RequestScoped
public class SprintBean extends BasicBean {

    private EstadoFacade estadoFacade = lookupEstadoFacade();
    private TareaFacade tareaFacade = lookupTareaFacade();
    private SprintFacade sprintFacade = lookupSprintFacade();
    private Date fecini;
    private Date fecfin;
    private String des;
    private Sprint sprint;
    private Sprint selectedSprint;
    private String sprintId;
    private List<Sprint> sprints;
    private String productoId;
    private List<Tarea> tareas;
    private String error = null;
    private ProductoSeleccionadoBean productoBean = null;
    private FacesContext context = null;

    public SprintBean() {
        context = FacesContext.getCurrentInstance();
        if (context != null) {
            productoBean = (ProductoSeleccionadoBean) context.getApplication().evaluateExpressionGet(context, "#{productoSeleccionadoBean}", ProductoSeleccionadoBean.class);
            productoId = productoBean.getProductoActual();
            buscarListadoSprintd();
        }

    }

    public String getProductoId() {
        return productoId;
    }

    public void setProductoId(String productoId) {
        this.productoId = productoId;
    }

    public final void buscarListadoSprintd() {
        sprints = sprintFacade.findByProyecto(productoId);
    }

    public void buscarTareasSprint() {
        tareas = tareaFacade.findByProyectoAndSprint(productoId, sprintId);
    }

    public ProductoSeleccionadoBean getProductoBean() {
        return productoBean;
    }

    public void setProductoBean(ProductoSeleccionadoBean productoBean) {
        this.productoBean = productoBean;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public Date getFecfin() {
        return fecfin;
    }

    public void setFecfin(Date fecfin) {
        this.fecfin = fecfin;
    }

    public Date getFecini() {
        return fecini;
    }

    public void setFecini(Date fecini) {
        this.fecini = fecini;
    }

    public Sprint getSprint() {
        return sprint;
    }

    public void setSprint(Sprint sprint) {
        this.sprint = sprint;
    }

    public List<Sprint> getSprints() {
        return sprints;
    }

    public void setSprints(List<Sprint> sprints) {
        this.sprints = sprints;
    }

    public Sprint getSelectedSprint() {
        return selectedSprint;
    }

    public void setSelectedSprint(Sprint selectedSprint) {
        this.selectedSprint = selectedSprint;
        setSprintId(selectedSprint.getId().toString());
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getSprintId() {
        return sprintId;
    }

    public void setSprintId(String sprintId) {
        this.sprintId = sprintId;
    }

    public List<Tarea> getTareas() {
        return tareas;
    }

    public void setTareas(List<Tarea> tareas) {
        this.tareas = tareas;
    }
    
    public void seleccionarSprint(String sprintID) {
        Sprint sp = sprintFacade.find(new Long(sprintID));
        setSelectedSprint(sp);
    }

    public String deleteSprint() {
        log.log(Level.INFO, "SprintBean.java: Borrado de Sprint {0}", selectedSprint.getDes());

        //quitamos asociación con tareas para no eliminarlas. Inicializamos fechas y estado=TODO
        buscarTareasSprint();
        Estado e = estadoFacade.find(new Long(1));

        if (tareas != null && tareas.size() > 0) {
            for (Tarea t : tareas) {
                t.setIdSprintFk(null);
                t.setFecfin(null);
                t.setFecini(null);
                t.setIdEstadoFk(e);
                tareaFacade.edit(t);
            }
        }

        //eliminamos el sprint
        sprintFacade.remove(selectedSprint);        

        if (context != null) {
            sprints.remove(selectedSprint);
            ProductoSeleccionadoBean productoBean = (ProductoSeleccionadoBean) context.
                    getApplication().
                    evaluateExpressionGet(context, "#{productoSeleccionadoBean}", ProductoSeleccionadoBean.class);

            Sprint sprintActual = sprintFacade.findSprintActualProyecto(productoId, new Date());
            if (sprintActual == null) {
                productoBean.setSprintActual("-1");
                return "main";
            } else {
                String idsprint = String.valueOf(sprintActual.getId());
                productoBean.setSprintActual(idsprint);
                return "";
            }
        }
        return "";

    }

    public String guardar() {
        if (datosValidos()) {
            Sprint sp = new Sprint();
            sp.setDes(des);
            sp.setFecini(fecini);
            sp.setFecfin(fecfin);
            Proyecto p = new Proyecto();
            p.setId(Long.parseLong(this.productoId));
            sp.setIdProyectoFk(p);
            sprintFacade.create(sp);

            log.log(Level.INFO, "Sprint Creado {0}", sp.getId());
            if (context != null) {
                return "main?faces-redirect=true&creado=1";
            } else {
                return "" + sp.getId();
            }            
        } else {
            log.log(Level.SEVERE, "Datos para crear Sprint NO VALIDOS");
            error = "Datos no válidos";
            return "";
        }

    }

    private SprintFacade lookupSprintFacade() {
        try {
            Context c = new InitialContext();
            return (SprintFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/SprintFacade!org.scrumpmt.ejb.SprintFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private boolean datosValidos() {
        if (des != null
                && fecini != null
                && fecfin != null
                && !des.equals("")
                && (fecini.compareTo(fecfin) < 0)) {
            return true;
        } else {
            return false;
        }
    }

    private EstadoFacade lookupEstadoFacade() {
        try {
            Context c = new InitialContext();
            return (EstadoFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/EstadoFacade!org.scrumpmt.ejb.EstadoFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private TareaFacade lookupTareaFacade() {
        try {
            Context c = new InitialContext();
            return (TareaFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/TareaFacade!org.scrumpmt.ejb.TareaFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
